<?php

namespace App\Services\UserInviteInfo;

use App\Models\User;
use App\Models\Product;
use App\Supports\Qrcode\WapQrcode;

class UserInviteInfo
{
	/**
	 * @var null | User
	 */
	protected $user = null;
	
	/**
	 * @var null | Product
	 */
	protected $product = null;
	
	protected $channel = 'wap'; // wap, app, mini

	protected $circle = null;
	
	
	public function __construct(User $user = null, Product $product = null, $channel = 'wap',$circle=null)
	{
		$this->user = $user;
		$this->product = $product;
		$this->channel = $channel;
		$this->circle = $circle;
	}
	
	public function inviteString()
	{
		return app(MakeUserInviteString::class, [
			'user' => $this->user,
			'product' => $this->product,
			'channel' => $this->channel
		])->make();
	}
	
	public function inviteRoute()
	{
		return app(MakeUserInviteRoute::class, [
			'user' => $this->user,
			'product' => $this->product,
			'channel' => $this->channel
		])->make();
	}
	
	public function inviteQrcode()
	{
		if (! $this->user) return null;
		$qrcodeMaker = new WapQrcode($this->user, $this->product);
		return $qrcodeMaker->make($this->inviteRoute());
	}
	
	public function userInvitePoster()
	{
		return app(MakeUserInvitePoster::class, [
			'user' => $this->user,
			'channel' => $this->channel
		])->make();
	}
	
	public function productInvitePoster()
	{
		return app(MakeProductInvitePoster::class, [
			'user' => $this->user,
			'product' => $this->product,
			'channel' => $this->channel
		])->make($this->product);
	}
	

	public function circleInvitePoster()
	{ 
		return app(MakeCircleInvitePoster::class, [
			'user' => $this->user,
			'circle' => $this->circle,
			'channel' => $this->channel
		])->make($this->circle);
	}


	public function userFromInviteCode(string $inviteCode)
	{
		return User::query()->where('invite_code', $inviteCode)->first();
	}
	
	public function userFromInviteString(string $inviteString)
	{
		$args = json_decode(base64_decode($inviteString), true);
		if (isset($args['inviter_id']) and isset($args['inviter_code'])) {
			return User::where('id', $args['inviter_id'])->first();
		} elseif (isset($args['inviter_code'])) {
			return User::where('invite_code', $args['inviter_code'])->first();
		}
		return null;
	}
}
